//
//  ActivityDetailViewController.m
//  SXH
//
//  Created by Ryan on 15/12/9.
//  Copyright © 2015年 lyss. All rights reserved.
//

#import "ActivityDetailViewController.h"
#import "CommonService.h"
#import "HotSpotModel.h"
#import "RecFoundViewController.h"
#import "SDWebImageManager.h"
#import "FindEntity.h"
#import "FindDetailViewController.h"
#import "WebViewController.h"
#import "MJRefresh.h"
@interface ActivityDetailViewController ()<UITableViewDelegate,UITableViewDataSource,ActivityPhotoCelldelegate>
{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
    BOOL segementload;
}
@property(nonatomic,strong) UISegmentedControl *segmentedControl;
@property(nonatomic,strong) UIButton *camera;
@end

@implementation ActivityDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initMainView];
//    [self getHotSpotData];
       [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getHotSpotData) name:Activity_refresh object:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return 260+180/320.0*SCREEN_WIDTH-180;
    }
    else
    {
        if ([self.photoArray count] > 0)
        {
            return ((self.photoArray.count/3+(self.photoArray.count%3>0?1:0))*SCREEN_WIDTH/3.0);
        }
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    return 35;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0 && indexPath.row ==0)
    {
        NSString *cellId = @"ActivityHeaderCell";
        ActivityHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:cellId owner:self options:nil]lastObject];
        }
        if (self.mainModel.contest_info)
        {
            cell.model = self.mainModel.contest_info;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickMore)];
            [cell.headContent addGestureRecognizer:tap];
            [cell.rightBtn addTarget:self action:@selector(clickMore) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }
    else
    {
        NSString *cellId = @"ActivityPhotoCell";
        ActivityPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:cellId owner:self options:nil]lastObject];
        }
        if ([self.photoArray count] > 0)
        {
            cell.photoArray = self.photoArray;
        }
        cell.delegate = self;
        return cell;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    [self compareString];
    if (self.mainModel) {
        NSString *type1 = [NSString stringWithFormat:@"精选 %@",self.mainModel.user_travel.tab1];
        NSString *type2 = [NSString stringWithFormat:@"全部 %@",self.mainModel.user_travel.tab2];
        NSString *type3 = [NSString stringWithFormat:@"获奖作品 %@",self.mainModel.user_travel.tab3];
        if (!self.segmentedControl)
        {
            self.segmentedControl = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:type1,type2,type3, nil]];
            self.segmentedControl.frame = CGRectMake(0, 0, SCREEN_WIDTH, 35);
            self.segmentedControl.tintColor = [UIColor whiteColor];
            [self.segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
            self.segmentedControl.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
            NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],
                                                     NSForegroundColorAttributeName: [UIColor blackColor]};
            [self.segmentedControl setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
            NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],
                                                       NSForegroundColorAttributeName: [UIColor colorWithRed:0.678f green:0.678f blue:0.678f alpha:1.00f]};
            [self.segmentedControl setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
            UIView *line1 = [[UIView alloc]init];
            UIView *line2 = [[UIView alloc]init];
            UIView *line3 = [[UIView alloc]init];
            UIView *line4 = [[UIView alloc]init];
            [self.segmentedControl addSubview:line1];
            [self.segmentedControl addSubview:line2];
            [self.segmentedControl addSubview:line3];
            [self.segmentedControl addSubview:line4];
            [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.top.equalTo(self.segmentedControl.mas_top);
                make.right.equalTo(@0);
                make.height.equalTo(@1);
            }];
            [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.segmentedControl);
                make.left.equalTo(@(SCREEN_WIDTH/3.0));
                make.width.equalTo(@1);
                make.height.equalTo(@20);
            }];
            [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.segmentedControl);
                make.left.equalTo(@(SCREEN_WIDTH/3.0*2));
                make.width.equalTo(@1);
                make.height.equalTo(@20);
            }];
            [line4 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.bottom.equalTo(self.segmentedControl.mas_bottom);
                make.right.equalTo(@0);
                make.height.equalTo(@1);
            }];
            line1.backgroundColor = [UIColor colorWithRed:0.969f green:0.969f blue:0.969f alpha:1.00f];
            line2.backgroundColor = [UIColor colorWithRed:0.969f green:0.969f blue:0.969f alpha:1.00f];
            line3.backgroundColor = [UIColor colorWithRed:0.969f green:0.969f blue:0.969f alpha:1.00f];
            line4.backgroundColor = [UIColor colorWithRed:0.969f green:0.969f blue:0.969f alpha:1.00f];
            self.segmentedControl.backgroundColor = [UIColor whiteColor];
            self.segmentedControl.selectedSegmentIndex = 1;//设置默认选择项索引
        }
        else
        {
            [self.segmentedControl setTitle:type1 forSegmentAtIndex:0];
            [self.segmentedControl setTitle:type2 forSegmentAtIndex:1];
            [self.segmentedControl setTitle:type3 forSegmentAtIndex:2];
        }

    }
       return self.segmentedControl;
}

-(void)segmentAction:(UISegmentedControl *)Seg{
    NSInteger Index = Seg.selectedSegmentIndex;
    NSLog(@"Index %zi", Index);
    page = 1;
    [self getHotSpotPhotoData:(Index+1)];
}


- (IBAction)doback:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)initMainView
{
    segementload = NO;
    self.tableView = [[UITableView alloc]init];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(62, 0, 0, 0));
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView reloadData];
    page = 1;
    [self addHeader];
    [self addFooter];
    _camera = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_camera];
    [_camera mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.equalTo(@50);
        make.height.equalTo(@50);
        make.bottom.equalTo(@(-10));
    }];
    [_camera setImage:[UIImage imageNamed:@"camera"] forState:UIControlStateNormal];
    [_camera addTarget:self action:@selector(upLoadImage) forControlEvents:UIControlEventTouchUpInside];
    [self addshake];

}

- (void) getHotSpotData
{
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *parm = @{@"id":self.spotId};
    [self showLoadingView:YES];
    [service getNetWorkData:parm
                       Path:ActivityDetail_PATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      self.mainModel = [[ActivityDetailModel alloc]initWithDictionary:[dic objectForKey:@"data"] error:nil];
                      if (page == 1) {
                          [self getHotSpotPhotoData:(self.segmentedControl.selectedSegmentIndex + 1) atPage:page RefreshView:nil];
                      }
                      else
                      {
                          [self getHotSpotPhotoData:(self.segmentedControl.selectedSegmentIndex + 1) atPage:page-1 RefreshView:nil];
                      }
                      [self.tableView reloadData];
                      [self showLoadingView:NO];
//                      [self initMainView];
//                      [self getHotSpotPhotoData:2];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self showLoadingView:NO];
                  }];
}

//parkid=1&page=1&limit=5&type=2
- (void) getHotSpotPhotoData:(NSInteger)index;
{
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *parm = @{@"parkid":self.mainModel.contest_info.park_id,
                           @"page":@"1",
                           @"limit":@"21",
                           @"type":[NSString stringWithFormat:@"%zi",index],
                           @"activity_id":self.spotId
                               };
    [self showLoadingView:YES];
    [service getNetWorkData:parm
                       Path:ActivityDetail_Photo_PATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      self.photoArray = [HotSpotModel arrayOfModelsFromDictionaries:[dic objectForKey:@"rows"]];
                      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
                      [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
                      [self showLoadingView:NO];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self showLoadingView:NO];
                  }];
}
- (void)compareString
{
    if (self.mainModel.user_travel.tab1.intValue == 0) {
        self.mainModel.user_travel.tab1 = @"";
    }
    if (self.mainModel.user_travel.tab2.intValue == 0) {
        self.mainModel.user_travel.tab2 = @"";
    }
    if (self.mainModel.user_travel.tab3.intValue == 0) {
        self.mainModel.user_travel.tab3 = @"";
    }
}

- (void)upLoadImage
{
    RecFoundViewController *mvc = [[RecFoundViewController alloc]init];
    ParkEntity *parkentity = [[ParkEntity alloc]init];
    parkentity.ID = self.mainModel.contest_info.park_id;
    parkentity.title = self.mainModel.contest_info.park_name;
    mvc.parkEntity = parkentity;
    mvc.ID = self.mainModel.contest_info.id;
    [self.navigationController pushViewController:mvc animated:YES];
}

- (IBAction)shareAction:(id)sender {
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    [[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:IMAGE_STRING(self.mainModel.contest_info.album_thumb)] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        NSArray* imageArray = [[NSArray alloc] initWithObjects:image, nil];
        
        [CommonService showShareActionSheet:self.view HUD:HUD
                                 ImageArray:imageArray
                                        URL:PORTAL_URL
                                      Title:self.mainModel.contest_info.title
                                    Content:self.mainModel.contest_info.headContent];
    }];
   
}

- (void)selectAtItem:(HotSpotModel *)model
{
    FindEntity *entity = [[FindEntity alloc]init];
    entity.ID = model.id;
    FindDetailViewController *vc = [[FindDetailViewController alloc] init];
    vc.findEntity = entity;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)clickMore
{
    WebViewController *mvc = [[WebViewController alloc]init];
    mvc.url = IMAGE_STRING(self.mainModel.contest_info.html);
    mvc.vcTitle = self.mainModel.contest_info.title;
    mvc.contentShare = _mainModel.contest_info.headContent ;
    [[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:IMAGE_STRING(self.mainModel.contest_info.album_thumb)] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        mvc.imageShare = image;}];
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated;
{
    [super viewWillAppear:animated];
}


- (void)addshake
{
    CABasicAnimation*animation=[CABasicAnimation
                                
                                animationWithKeyPath:@"transform"];
    animation.duration=0.2;
    animation.repeatCount = 100000;
    animation.autoreverses=YES;
    animation.fromValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                         
                         (_camera.layer.transform, -0.03, 0.0, 0.0, 0.03)];
    animation.toValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                       
                       (_camera.layer.transform, 0.03, 0.0, 0.0, 0.03)];
    [_camera.layer addAnimation:animation forKey:@"wiggle"];
}

- (void) getHotSpotPhotoData:(NSInteger)index atPage:(int)pageNo  RefreshView:(MJRefreshBaseView *)refreshView
{
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *parm = @{@"id":self.spotId};
    [service getNetWorkData:parm
                       Path:ActivityDetail_PATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      self.mainModel = [[ActivityDetailModel alloc]initWithDictionary:[dic objectForKey:@"data"] error:nil];
                      CommonService *service = [[CommonService alloc] init];
                      NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
                      NSDictionary *parm = @{@"parkid":self.mainModel.contest_info.park_id,
                                             @"page":strPageNo,
                                             @"limit":@"21",
                                             @"type":[NSString stringWithFormat:@"%zi",index],
                                             @"activity_id":self.spotId
                                             };
                      [service getNetWorkData:parm
                                         Path:ActivityDetail_Photo_PATH
                                    Successed:^(id entity) {
                                        NSDictionary *dic = (NSDictionary *)entity;
                                        if (pageNo == 1) {
                                            [self.photoArray removeAllObjects];
                                            self.photoArray = [HotSpotModel arrayOfModelsFromDictionaries:[dic objectForKey:@"rows"]];
                                        }
                                        else
                                        {
                                            NSArray * array = [HotSpotModel arrayOfModelsFromDictionaries:[dic objectForKey:@"rows"]];
                                            if ([array count] == 0) {
                                                page --;
                                            }
                                            else
                                            {
                                                [self.photoArray addObjectsFromArray:array];
                                            }
                                        }

                                        [self doneWithView:refreshView];

                                        
                                        
                                    } Failed:^(NSInteger errorCode, NSString *message) {
                                        page --;
                                        [self doneWithView:refreshView];
                                    }];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self showLoadingView:NO];
                  }];
    
}
- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        page = 1;
        if (self.segmentedControl) {
            [self getHotSpotPhotoData:(self.segmentedControl.selectedSegmentIndex + 1) atPage:page RefreshView:refreshView];
        }
        else
        {
            [self getHotSpotPhotoData:2 atPage:page RefreshView:refreshView];
        }
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getHotSpotPhotoData:(self.segmentedControl.selectedSegmentIndex + 1) atPage:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}


- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}
@end
